"""
@Author：WangYuXiang
@E-mile：Hill@3io.cc
@CreateTime：2021/4/22 10:53
@DependencyLibrary：无
@MainFunction：无
@FileDoc： 
    signals.py
    文件说明
@ChangeHistory:
    datetime action why
    example:
    2021/4/22 10:53 change 'Fix bug'
        
"""

import json
import pathlib
from apps import app, apps_helper
from common.auth.models import PermissionModel, UserModel, GroupModel, RoleModel

# apps_helper


def collection_permissions():
    file_name = 'permission.json'
    for app_name, app_info in apps_helper.apps.items():
        module_path = app_info.get('path')
        path = module_path / file_name
        if not path.exists():
            continue
        with open(path, 'r', encoding='utf8') as f:
            permission_dict = json.loads(f.read())
            for classify_code, classify_info in permission_dict.items():
                classify_name = classify_info['label']
                permissions = classify_info['permissions']
                for code, name in permissions.items():
                    yield code, name, classify_code, classify_name


@app.listener('before_server_start')
async def load_permission(app, loop):
    """在服务器启动时加载权限"""
    new_perm_code_list = []
    old_perm_code_list = await PermissionModel.all().values('code')

    for code, name, classify_code, classify_name in collection_permissions():
        perm_dict = {
            'code': code, 'name': name, 'classify_code': classify_code, 'classify_name': classify_name
        }
        permission = await PermissionModel.get_or_none(code=code)
        if permission:
            perm_dict.pop('code')
            await permission.update_from_dict(perm_dict)
        else:
            await PermissionModel.create(**perm_dict)
        new_perm_code_list.append(code)
    wait_del_code_list = [
        i['code'] for i in old_perm_code_list if i['code'] not in new_perm_code_list]
    await PermissionModel.filter(code__in=wait_del_code_list).delete()


@app.listener('before_server_start')
async def add_superadmin(app, loop):
    """在服务器启动时加载权限"""
    group = await GroupModel.filter(code='system_group').first()
    if not group:
        group = await GroupModel.create(**{
            'code': 'system_group',
            'name': '系统组织',
        })
    role = await RoleModel.filter(code='super_admin').first()
    if not role:
        role = await RoleModel.create(**{
            'code': 'super_admin',
            'name': '超级管理员',
            'group_id': group.pk
        })
    user = await UserModel.filter(account='super_admin').first()
    if not user:
        user = await UserModel.create(**{
            'account': 'super_admin',
            'pwd': UserModel.encryption_password('123.123'),
            'nickname': '超级管理员',
            'is_super_admin': True,
            'is_active': True
        })
    await user.roles.add(role)
